package cn.fufeiii.bt.common.util;


import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.springframework.data.util.Pair;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * 文件工具类
 *
 * @author FuFei
 */
public class FileUtil {

    /**
     * 图片尺寸大小校验
     *
     * @param file *
     * @return *
     */
    public static Pair<Integer, Integer> getImageSize(MultipartFile file) {
        try {
            BufferedImage image = ImageIO.read(file.getInputStream());
            return Pair.of(image.getWidth(), image.getHeight());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * LocalFile转为MultipartFile
     *
     * @param file *
     * @return *
     */
    public static MultipartFile covertToMultipartFile(File file) {
        return covertToMultipartFile(file, file.getName());
    }

    /**
     * file转为MultipartFile
     *
     * @param file *
     * @return *
     */
    public static MultipartFile covertToMultipartFile(File file, String fileName) {
        FileItem item = new DiskFileItemFactory().createItem("file", null, true, fileName);
        int bytesRead;
        byte[] buffer = new byte[8192];
        try (FileInputStream fis = new FileInputStream(file); OutputStream os = item.getOutputStream()) {
            while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return new CommonsMultipartFile(item);
    }
}
